<!DOCTYPE html>
<html lang="en">
<head>
    <title>用户列表</title>


    <script src="/static/js/jquery-1.12.4.min.js" type="text/javascript"></script>

    <link href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">

    <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>

<!--修改模态框-->
<div class="modal fade" id="empUpdateModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="update">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empName_input_add" class="col-sm-2 control-label">员工姓名</label>
                        <div class="col-sm-10">
                            <p id="empName_update_static"></p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_input_add" class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="email" id="email_input_update" placeholder="lisi@bdqn.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender"  value="M" checked> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" value="W"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">部门名称</label>
                        <div class="col-sm-4">
                            <select class="form-control" id="update_dept" name="dId">

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="update_save_btn">更新</button>
            </div>
        </div>
    </div>
</div>

<!--新增模态框-->
<div class="modal fade" id="empAddModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">员工新增</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empName_input_add" class="col-sm-2 control-label">员工姓名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="empName_input_add" name="empName" placeholder="empName">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_input_add" class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="email" id="email_input_add" placeholder="lisi@bdqn.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender"  value="M" checked> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" value="W"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">部门名称</label>
                        <div class="col-sm-4">
                            <select class="form-control" id="add_dept" name="dId">

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="add_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="container">

    <!--标题-->
    <h1 class="h1">ssm-crud</h1>

    <!--按钮-->
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button type="button" class="btn btn-success" id="emp_add_btn">新增</button>
            <button type="button" class="btn btn-danger" id="batch_delete">删除</button>
        </div>

    </div>

    <!--数据-->
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="table_emp_info">
                <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="check_all">
                    </th>
                    <th>ID</th>
                    <th>empName</th>
                    <th>gender</th>
                    <th>email</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>


                </tbody>

            </table>
        </div>
    </div>

    <!--分页-->
    <div class="row">
        <!--分页信息-->
        <div class="col-md-6" id="page_info">

        </div>
        <!--分页条-->
        <div class="col-md-6" id="page_nav">

        </div>
    </div>
</div>


<script>
    //页面加载完毕就发送查询请求
    $(function () {
        to_page(1);
    })
    var total,currentPage;

    // 查询数据
    function to_page(pageNum) {
        $.ajax({
            url: "/employee/getEmployeeListByJson",
            data: "pageNum=" + pageNum,
            type: "get",
            success: function (data) {
                // 加载员工列表
                emp_info(data);

                // 加载分页信息
                page_info(data);

                // 分页条
                page_nav(data);
            }
        });
    }

    // 加载员工列表
    function emp_info(result) {
        // 清空之前内容
        $("#table_emp_info tbody").empty();
        var emps = result.extend.pageInfo.list;
        $.each(emps, function (index, emp) {
            var checkBoxTd=$("<td><input type='checkbox' class='check_item'></td>")
            var empIdTd = $("<td></td>").append(emp.empId);
            var empNameTd = $("<td></td>").append(emp.empName);
            var genderTd = $("<td></td>").append(emp.gender == "M" ? "男" : "女");
            var emailTd = $("<td></td>").append(emp.email);
            var deptNameTd = $("<td></td>").append(emp.department.deptName);
            var editBtn = $("<button type='button' class='btn btn-success glyphicon glyphicon-pencil btn-sm edit_Update'>修改</button>");
            editBtn.attr("edit_id",emp.empId);
            var delBtn = $("<button type='button' class='btn btn-danger glyphicon glyphicon-trash btn-sm del_btn'>删除</button>");
            delBtn.attr("delete",emp.empId);
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);

            $("<tr></tr>").append(checkBoxTd)
                .append(empIdTd)
                .append(empNameTd)
                .append(genderTd)
                .append(emailTd)
                .append(deptNameTd)
                .append(btnTd)
                .appendTo($("#table_emp_info tbody"));

        });
    }

    // 加载分页信息
    function page_info(result) {
        $("#page_info").empty();
        $("#page_info").append("当前在 " + result.extend.pageInfo.pageNum +"  页, 共 " + result.extend.pageInfo.pages +  " 页, 共" + result.extend.pageInfo.total+  "条记录");
        total = result.extend.pageInfo.total;
        currentPage=result.extend.pageInfo.pageNum;
    }

    // 分页条
    function page_nav(result) {
        $("#page_nav").empty();
        var ul = $("<ul class='pagination'></ul>");
        var firstPageLi = $("<li><a href='#'>首页</a> </li>");
        var prePageLi = $("<li><a href='#'><span>&laquo;</span></a></li>");

        ul.append(firstPageLi).append(prePageLi);

        // 判断是否有上一页,有的话跳转,否则禁用
        if (result.extend.pageInfo.hasPreviousPage == false) {
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        }else {
            firstPageLi.click(function () {
                to_page(1);
            });
            prePageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum - 1);
            });
        }

        // 遍历页码号
        $.each(result.extend.pageInfo.navigatepageNums, function (index, pageNum) {
            var numLi = $("<li></li>").append($("<a href='#'></a>").append(pageNum));
            ul.append(numLi);

            // 判断是否当前页,是的话高亮显示,否则的话跳转
            if (result.extend.pageInfo.pageNum == pageNum) {
                numLi.addClass("active");
            }else {
                numLi.click(function () {
                    to_page(pageNum);
                });
            }
        });

        var nextPageLi = $("<li><a href='#'><span>&raquo;</span></a></li>");
        var lastPageLi = $("<li><a href='#'>末页</a> </li>");
        ul.append(nextPageLi).append(lastPageLi);

        // 判断是否有下一页,有的话跳转,否则禁用
        if (result.extend.pageInfo.hasNextPage == false) {
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        }else {
            nextPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum + 1);
            });
            lastPageLi.click(function () {
                to_page(result.extend.pageInfo.pages);
            });
        }
        var nav = $("<nav aria-label='Page navigation'></nav>").append(ul);
        nav.appendTo($("#page_nav"));
    }

    // 点击新增按钮弹出模态框
    $("#emp_add_btn").click(function () {
        reset_form("#empAddModel form");
        // 查询部门列表
        getDeptList("#add_dept");

        // 弹出模态框
        $("#empAddModel").modal({
            backdrop: "static"
        })
    });

/*修改按钮*/
    $(document).on("click",".edit_Update",function () {
        /*调用查询员工的方法*/
        var empIds=$(this).attr("edit_id")
        /*给编辑按钮增加ID*/
        $("#update_save_btn").attr("edit",$(this).attr("edit_id"));
        getEmployeeById(empIds)
      /*查询部门*/
      getDeptList("#update_dept")
        // 弹出修改的模态框
        $("#empUpdateModel").modal({
            backdrop: "static"
        })
    })

    // 查询部门列表并渲染
    function getDeptList(ele) {
        // 清空之前内容
        $(ele).empty();
        $.ajax({
            url: "/department/getDepartmentList",
            type: "get",
            success: function (data) {
                //console.log(data);
                $.each(data.extend.list, function () {
                    var optionEle = $("<option></option>").attr("value", this.deptId).append(this.deptName);
                    optionEle.appendTo($(ele));
                })
            }
        });
    }

    // 清除表单样式及内容
    function reset_form(ele) {
        // 清除内容
        $(ele)[0].reset();

        // 清除样式
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").removeClass();
    }

    // 验证表单
    function check_form() {
        var empName = $("#empName_input_add").val();
        var regEmpName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        // 验证用户名
        if (!regEmpName.test(empName)) {
            //alert("用户名可以是 2-5 位中文或6-16 位英文");
            show_form_msg("#empName_input_add", "error", "用户名可以是 2-5 位中文或6-16 位英文");
            // $("#empName_input_add").parent().addClass("has-error");
            // $("#empName_input_add").next("span").text("用户名可以是 2-5 位中文或6-16 位英文");
            return false;
        }else {
            show_form_msg("#empName_input_add", "success", "");
            /*$("#empName_input_add").parent().addClass("has-success");
            $("#empName_input_add").next("span").text("");*/
        }


        var email = $("#email_input_add").val();
        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!regEmail.test(email)) {
            //alert("邮箱格式不正确");
            show_form_msg("#email_input_add", "error", "邮箱不合法");
            return false;
        }else {
            show_form_msg("#email_input_add", "success", "");
        }
        return true;
    }

    // 显示提示正确还是错误的信息
    function show_form_msg(ele, status, msg) {
        $(ele).parent().removeClass("has-error has-success");
        $(ele).next("span").text("");
        if (status === "error") {
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);
        }else if (status === "success") {
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text("");
        }
    }

    // 验证员工名是否唯一
    $("#empName_input_add").on("input propertychange", function () {
        var empName = $("#empName_input_add").val();
        $.ajax({
            url: "/employee/checkEmpName",
            type: "get",
            data: {"empName": empName},
            success: function (data) {
                if (data.code === 200) {
                    show_form_msg("#empName_input_add", "success", "用户名可用");
                    $("#add_save_btn").attr("ajax_va", "success");
                }
                if (data.code === 500) {
                    show_form_msg("#empName_input_add", "error", "用户名不可用");
                    $("#add_save_btn").attr("ajax_va", "error");
                }
            }
        });
    });


    // 保存员工信息
    $("#add_save_btn").click(function () {
        // 验证用户名是否可用
        if ($(this).attr("ajax_va") === "error") {
            return false;
        }
        // 验证表单
        if (!check_form()) {
            return false;
        }
        $.ajax({
            url: "/employee/saveEmployee",
            type: "post",
            data: $("#empAddModel form").serialize(),
            success: function (data) {
                // 先关闭模态框
                $("#empAddModel").modal('hide');
                // 跳转至最后一页, 传总条数
                to_page(total);
            }

        });
    });

/*根据ID查询出员工的信息*/
    function getEmployeeById(empId) {
$.ajax({
    url:"/employee/getEmployeeById/"+empId,
    type:"get",
    success:function (data) {
console.log(data)
        var emp=data.extend.employee;
            $("#empName_update_static").text(emp.empName);
        $("#email_input_update").val(emp.email);
        $("#empUpdateModel input[name=gender]").val([emp.gender]);
        $("#update_dept").val([emp.dId]);
    }
})
    }

    /*修改保存*/
    $("#update_save_btn").click(function () {

        var email = $("#email_input_update").val();
        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!regEmail.test(email)) {
            //alert("邮箱格式不正确");
            show_form_msg("#email_input_update", "error", "邮箱不合法");
            return false;
        }else {
            show_form_msg("#email_input_update", "success", "");
        }
var empId=$("#update_save_btn").attr("edit");
        //发送请求
        $.ajax({
url:"/employee/updateEmployee/"+empId,
            type:"put",
            data:$("#empUpdateModel form").serialize(),
            success:function (data) {
//关闭模态框
                $("#empUpdateModel").modal('hide');
                /*跳转回当前页*/
                to_page(currentPage);
            }
        })
    });

    /*单个删除*/
    $(document).on("click",".del_btn",function () {
        //先取出删除按钮中存储的ID
        var empName=$(this).parents("tr").find("td:eq(2)").text();
        var empId=$(this).attr("delete")
        /*根据ID删除单个*/
        if(confirm("确认要删除员工姓名为"+empName+"的信息吗")){
$.ajax({
    url:"/employee/delEmployeeById/"+empId,
    type:"delete",
    success:function (data) {
        $("#empUpdateModel").modal('hide');
        /*跳转回当前页*/
        to_page(currentPage);
    }
})
        }
    })

    /*全选/全不选*/
    $("#check_all").click(function () {
$(".check_item").prop("checked",$(this).prop("checked"))
    })

    /*五个单选全部勾选上，默认父级也要被选上*/
    $(document).on("click",".check_item",function () {
    /*判断数组长是否等于5*/
        var flag=$(".check_item:checked").length==$(".check_item").length;
        $("#check_all").prop("checked",flag);
    })

    /*发送请求*/
    /*点击批量删除按钮则发送ajax请求*/
    $("#batch_delete").click(function () {
            var empNames="";
            var ids="";
            $.each($(".check_item:checked"),function () {
            empNames+=$(this).parents("tr").find("td:eq(2)").text()+",";
            ids+=$(this).parents("tr").find("td:eq(1)").text()+"-";
            });
          /*去除多于字符串*/
        empNames=empNames.substring(0,empNames.length-1);
        //发送请求
        if(confirm("确认要删除员工名字id为"+ids+"的信息吗")){
            $.ajax({
                url:"/employee/delEmployeeByIds/"+ids,
                type:"delete",
                success:function (data) {
                    $("#empUpdateModel").modal('hide');
                    /*跳转回当前页*/
                    to_page(currentPage);
                }
            })
        }
    })
</script>
</body>
</html>
